import { isPromise } from '@/utils/interceptor'
import { defineComponent, ref } from 'vue'
import './Modal.less'

export default defineComponent({
	name: 'Modal',
	props: {
		show: {
			type: Boolean,
			default: false
		},
		title: String,
		content: {
			type: String,
			default: '内容'
		},
		cancelText: {
			type: String,
			default: '取消'
		},
		confirmText: {
			type: String,
			default: '确认'
		},
		showCancelBtn: {
			type: Boolean,
			default: true
		},
		showConfirmBtn: {
			type: Boolean,
			default: true
		},
		confirm: {
			type: Function,
			default: () => {}
		},
		cancel: {
			type: Function,
			default: () => {}
		},
		// 用于移除组件的方法
		unmount: {
			type: Function,
			default: () => {}
		}
	},
	setup(props, { emit }) {
		const confirmLoading = ref(false)
		const cancelLoading = ref(false)

		const close = () => {
			emit('update:show', false)
			setTimeout(() => {
				props.unmount()
			}, 0)
		}

		const onConfirm = async () => {
			if (props.confirm) {
				const confirm = props.confirm.apply(props)
				if (isPromise(confirm)) {
					confirmLoading.value = true
					await confirm
					confirmLoading.value = false
				}
				close()
			}
		}

		const onCancel = async () => {
			if (props.cancel) {
				const cancel = props.cancel.apply(props)
				if (isPromise(cancel)) {
					cancelLoading.value = true
					await cancel
					cancelLoading.value = false
				}
				close()
			}
		}

		return () => {
			const leftBtn = () => {
				return cancelLoading.value ? (
					<div class="btns-loading animate-loading"></div>
				) : (
					<div class="btns modal-btns-cancel" onClick={onCancel}>
						{props.cancelText}
					</div>
				)
			}
			const rightBtn = () => {
				return confirmLoading.value ? (
					<div class="btns-loading animate-loading"></div>
				) : (
					<div class="btns modal-btns-confirm" onClick={onConfirm}>
						{props.confirmText}
					</div>
				)
			}
			return (
				<div class="modal" v-show={props.show}>
					<div class="modal-mask"></div>
					<div class="modal-container">
						<div class="modal-header">
							<div class="modal-title" v-show={props.title}>
								{props.title}
							</div>
							<div class="modal-content">{props.content}</div>
						</div>
						<div class="modal-footer">
							<div class="modal-footer-left" v-show={props.showCancelBtn}>
								{leftBtn()}
							</div>
							<div class="modal-footer-right" v-show={props.showConfirmBtn}>
								{rightBtn()}
							</div>
						</div>
					</div>
				</div>
			)
		}
	}
})
